package puzzle.projecteuler.p300;



public class Problem235C {
	

	/**
	 * answer	: 1.002322108633
	 * time cost: 16 ms
	 * 注意：结果四舍五入。
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
	
		long s = System.currentTimeMillis();
		double r1 = 1.002;	//T(r1) > 0
		double r2 = 1.003;	//T(r2) < 0
		do {
			double r = (r1+ r2)/2.0;
			double t = T(r);
			if (t > 0) {
				r1 = r;
			} else if (t < 0) {
				r2 = r;
			} else {
				r1 = r;
				r2 = r;
			}
		} while (r2 - r1 > 1.0e-15);
		System.out.println("T(" + r1 + ")=" + T(r1));
		System.out.println("T(" + r2 + ")=" + T(r2));
		System.out.println(String.valueOf(r2).substring(0, 14));
		System.out.println((System.currentTimeMillis()-s) + " ms");
	}

	/**
	 * S(n, r) = 900 *(r^n-1)/(r-1) - 3*[(n+1)*r^n-1]/(r-1) + 3*(r^(n+1)-r)/(r-1)/(r-1)
	 * 这个公式只在r!=1.0f的时候成立。幸运的是，这个问题的满足这个条件。
	 * @param n
	 * @param r
	 * @return
	 */
	private static double S(int n, double r) {
		
		double rn = Math.pow(r, n);	//r^n
		double s1 = (rn-1)/(r-1);
		double s2 = ((n+1)*rn-1)/(r-1);
		double s3 = s1*r/(r-1);
		return 900.0f*s1 - 3.0f*(s2-s3);
	}
	
	private static double T(double r) {
		
		return S(5000, r) + 6.0e11;
	}
}
